const fs = require('fs').promises;
const path = require('path');
const axios = require('axios');
const dayjs = require('dayjs');

class FeiFanService {
    constructor() {
        this.dataFile = path.join(__dirname, './data/tokens.json');
        this.ensureDataFile();
    }

    /** 获取模拟浏览器的请求头 */
    getBrowserHeaders(token, entityId = null) {
        const headers = {
            'accept': 'application/json',
            'accept-encoding': 'gzip, deflate, br, zstd',
            'accept-language': 'zh-CN,zh;q=0.9',
            'cache-control': 'no-cache',
            'content-type': 'application/json',
            'origin': 'https://feifan.iflytek.com',
            'pragma': 'no-cache',
            'sec-ch-ua': '"Not;A=Brand";v="99", "Google Chrome";v="139", "Chromium";v="139"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'timer': Date.now().toString(),
            'token': token,
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36'
        };

        // 如果有entityId，添加referer
        if (entityId) {
            headers['referer'] = `https://feifan.iflytek.com/userCenter/forumArticleDetail/?articleid=${entityId}`;
        }

        return headers;
    }

    /** 通用请求配置 */
    getRequestConfig() {
        return {
            timeout: 30000,
            validateStatus: function (status) {
                return status >= 200 && status < 300;
            }
        };
    }

    /** 确保数据文件存在*/
    async ensureDataFile() {
        try {
            await fs.access(this.dataFile);
        } catch {
            // 如果文件不存在，创建空的数据文件
            await fs.mkdir(path.dirname(this.dataFile), { recursive: true });
            await fs.writeFile(this.dataFile, JSON.stringify([]));
        }
    }

    /** 读取所有 token */
    async selectAllUserToken() {
        try {
            const data = await fs.readFile(this.dataFile, 'utf8');
            return JSON.parse(data);
        } catch (error) {
            console.error('读取 token 失败:', error);
            return error;
        }
    }

    /** 读取某个用户信息 */
    async selectUserTokenByUsername(userName) {
        try {
            const data = await fs.readFile(this.dataFile, 'utf8');
            return JSON.parse(data).find(o => o.userName === userName);
        } catch (error) {
            console.error('读取 token 失败:', error);
            return error;
        }
    }

    /** 添加或更新 token */
    async addOrUpDateToken(param) {
        try {
            // 校验 token
            const response = await axios.post(
                'https://feifan.iflytek.com/teclib-feifan-service/userApi/signin/signin',
                null,
                {
                    headers: {
                        'Content-Type': 'application/json;charset=UTF-8',
                        'token': param.token
                    }
                }
            );

            if (response.data.msg !== 'SUCCESS') {
                return 'token错误请重新输入';
            }

            // 读取现有数据
            const tokens = await this.selectAllUserToken();

            // 更新或添加新 token
            const index = tokens.findIndex(t => t.userName === param.userName);
            if (index >= 0) {
                tokens[index] = param;
            } else {
                tokens.push(param);
            }

            // 保存数据
            await fs.writeFile(this.dataFile, JSON.stringify(tokens, null, 2));
            return '恭喜，维护成功';
        } catch (error) {
            console.error('更新token失败:', error);
            return 'token错误请重新输入';
        }
    }

    /**  删除 token */
    async deleteToken(userName) {
        try {
            // 读取现有数据
            const tokens = await this.selectAllUserToken();

            // 更新或添加新 token
            const newTokens = tokens.filter(t => t.userName !== userName);


            // 保存数据
            await fs.writeFile(this.dataFile, JSON.stringify(newTokens, null, 2));
            return true;
        } catch (error) {
            console.error('删除失败:', error);
            return false;
        }
    }

    /** 一键执行 */
    async jobStartAll() {
        try {
            const feifanTokenParams = await this.selectAllUserToken();

            for (const feifanTokenParam of feifanTokenParams) {
                console.log(`${feifanTokenParam.userName}----》执行开始！`);

                // 使用浏览器模拟请求头
                const headers = this.getBrowserHeaders(feifanTokenParam.token);
                const config = this.getRequestConfig();

                // 1. 请求签到任务
                try {
                    const signinResponse = await axios.post(
                        'https://feifan.iflytek.com/teclib-feifan-service/userApi/signin/signin',
                        null,
                        { ...config, headers }
                    );

                    if (signinResponse.data.msg === 'SUCCESS') {
                        console.log('签到成功!');
                    } else {
                        console.log('签到失败!');
                        continue;
                    }
                } catch (error) {
                    console.error('签到请求失败:', error);
                    continue;
                }

                // 2. 资源评分任务
                const event = '资源评分';
                const resourceScoreList = await this.getObjects(headers, event);
                const resourceScoreCount = 1 - resourceScoreList.length;

                if (resourceScoreCount > 0) {
                    try {
                        const resourceScoreResponse = await axios.post(
                            'https://feifan.iflytek.com/teclib-feifan-service/userApi/res/scoring',
                            {
                                resourceId: '213',
                                nodeId: '466',
                                score: 100
                            },
                            { ...config, headers }
                        );

                        if (resourceScoreResponse.data.msg === 'SUCCESS') {
                            console.log('技术评分成功!');
                        } else {
                            console.log('技术评分失败!');
                        }
                    } catch (error) {
                        console.error('技术评分请求失败:', error);
                    }
                }

                // 3. 水贴任务
                const commentEvent = '15字以上评论';
                const commentList = await this.getObjects(headers, commentEvent);
                const commentCount = 3 - commentList.length;

                if (commentCount > 0) {
                    for (let i = 1; i <= commentCount; i++) {
                        try {
                            const commentResponse = await axios.post(
                                'https://feifan.iflytek.com/sns-service/userApi/comment/comment/post',
                                {
                                    username: `/${feifanTokenParam.userName}`,
                                    entityId: '29032',
                                    content: '<p>专业自由的飞帆星球由你我共建。</p>',
                                    parentId: null,
                                    imgList: [],
                                    entityTitle: '经验贴 - 飞帆技术社区灌水专用文章'
                                },
                                { ...config, headers }
                            );

                            await new Promise(resolve => setTimeout(resolve, 20000));

                            if (commentResponse.data.msg === 'SUCCESS') {
                                console.log(`第${i}次水贴成功!`);
                            } else {
                                console.log(`第${i}次水贴失败!`);
                            }
                        } catch (error) {
                            console.error(`第${i}次水贴请求失败:`, error);
                        }
                    }
                }

                // 4. 收藏/取消收藏任务
                const collectEvent = '收藏专题文章/专题/资源';
                const collectList = await this.getObjects(headers, collectEvent);
                const collectCount = 3 - collectList.length;

                if (collectCount > 0) {
                    try {
                        // 获取默认收藏夹
                        const starResponse = await axios.get(
                            `https://feifan.iflytek.com/teclib-feifan-app/post/listCollectionGroup?postId=47705&username=${feifanTokenParam.userName}`,
                            { ...config, headers }
                        );

                        const starId = starResponse.data.data[0].id;

                        for (let i = 1; i <= collectCount; i++) {
                            // 取消收藏
                            const uncollectResponse = await axios.post(
                                'https://feifan.iflytek.com/sns-service/userApi/collect/unCollect/post',
                                {
                                    groupIdSet: [starId],
                                    entityId: 47654
                                },
                                { ...config, headers }
                            );

                            await new Promise(resolve => setTimeout(resolve, 10000));

                            if (uncollectResponse.data.msg === 'SUCCESS') {
                                console.log(`第${i}次取消收藏成功!`);
                            } else {
                                console.log(`第${i}次取消收藏失败!`);
                            }

                            // 收藏
                            const collectResponse = await axios.post(
                                'https://feifan.iflytek.com/sns-service/userApi/collect/collect/post',
                                {
                                    groupIdSet: [starId],
                                    entityId: 47654
                                },
                                { ...config, headers }
                            );

                            await new Promise(resolve => setTimeout(resolve, 20000));

                            if (collectResponse.data.msg === 'SUCCESS') {
                                console.log(`第${i}次收藏成功!`);
                            } else {
                                console.log(`第${i}次收藏失败!`);
                            }
                        }
                    } catch (error) {
                        console.error('收藏/取消收藏请求失败:', error);
                    }
                }

                // 5. 资源下载任务
                const downloadEvent = '下载资源';
                const downloadList = await this.getObjects(headers, downloadEvent);
                const downloadCount = 1 - downloadList.length;

                if (downloadCount > 0) {
                    try {
                        const downloadResponse = await axios.get(
                            'https://feifan.iflytek.com/res-service/userApi/basicRes/getResourceDownloadAddress?resourceId=2300&versionId=3527',
                            { ...config, headers }
                        );

                        if (downloadResponse.data.code === 201) {
                            console.log('下载资源成功!');
                        } else {
                            console.log('下载资源失败!');
                        }
                    } catch (error) {
                        console.error('下载资源请求失败:', error);
                    }
                }

                // 6. 每日阅读任务
                try {
                    const postsResponse = await axios.get(
                        'https://feifan.iflytek.com/teclib-feifan-app/post/pagePostsBySubject?page=1&size=20&keyword=&orderEnum=firstPublishedTime',
                        { ...config, headers }
                    );

                    const posts = postsResponse.data.data.data;
                    for (let i = 0; i < 10; i++) {
                        const postId = posts[i].postId;
                        await axios.get(
                            `https://feifan.iflytek.com/teclib-feifan-app/post/getPostDetail?postId=${postId}`,
                            { ...config, headers }
                        );
                    }
                } catch (error) {
                    console.error('阅读任务请求失败:', error);
                }

                console.log(`${feifanTokenParam.userName}执行结束！`);
            }
        } catch (error) {
            console.error('任务执行失败:', error);
        }
    }

    /** 开始某个用户的刷分任务 */
    async jobStart(userName) {
        try {
            const feifanTokenParam = await this.selectUserTokenByUsername(userName);

            console.log(`${feifanTokenParam.userName}----》执行开始！`);

            // 使用浏览器模拟请求头
            const headers = this.getBrowserHeaders(feifanTokenParam.token);
            const config = this.getRequestConfig();

            // 1. 请求签到任务
            try {
                const signinResponse = await axios.post(
                    'https://feifan.iflytek.com/teclib-feifan-service/userApi/signin/signin',
                    null,
                    { ...config, headers }
                );

                if (signinResponse.data.msg === 'SUCCESS') {
                    console.log('签到成功!');
                } else {
                    console.log('签到失败!');
                }
            } catch (error) {
                console.error('签到请求失败:', error);
            }

            // 2. 资源评分任务
            const event = '资源评分';
            const resourceScoreList = await this.getObjects(headers, event);
            const resourceScoreCount = 1 - resourceScoreList.length;

            if (resourceScoreCount > 0) {
                try {
                    const resourceScoreResponse = await axios.post(
                        'https://feifan.iflytek.com/teclib-feifan-service/userApi/res/scoring',
                        {
                            resourceId: '213',
                            nodeId: '466',
                            score: 100
                        },
                        { ...config, headers }
                    );

                    if (resourceScoreResponse.data.msg === 'SUCCESS') {
                        console.log('技术评分成功!');
                    } else {
                        console.log('技术评分失败!');
                    }
                } catch (error) {
                    console.error('技术评分请求失败:', error);
                }
            }

            // 3. 水贴任务
            const commentEvent = '15字以上评论';
            const commentList = await this.getObjects(headers, commentEvent);
            const commentCount = 3 - commentList.length;

            if (commentCount > 0) {
                for (let i = 1; i <= commentCount; i++) {
                    try {
                        const commentResponse = await axios.post(
                            'https://feifan.iflytek.com/sns-service/userApi/comment/comment/post',
                            {
                                username: `/${feifanTokenParam.userName}`,
                                entityId: '29032',
                                content: '<p>专业自由的飞帆星球由你我共建。</p>',
                                parentId: null,
                                imgList: [],
                                entityTitle: '经验贴 - 飞帆技术社区灌水专用文章'
                            },
                            { ...config, headers }
                        );

                        await new Promise(resolve => setTimeout(resolve, 20000));

                        if (commentResponse.data.msg === 'SUCCESS') {
                            console.log(`第${i}次水贴成功!`);
                        } else {
                            console.log(`第${i}次水贴失败!`);
                        }
                    } catch (error) {
                        console.error(`第${i}次水贴请求失败:`, error);
                    }
                }
            }

            // 4. 收藏/取消收藏任务
            const collectEvent = '收藏专题文章/专题/资源';
            const collectList = await this.getObjects(headers, collectEvent);
            const collectCount = 3 - collectList.length;

            if (collectCount > 0) {
                try {
                    // 获取默认收藏夹
                    const starResponse = await axios.get(
                        `https://feifan.iflytek.com/teclib-feifan-app/post/listCollectionGroup?postId=47705&username=${feifanTokenParam.userName}`,
                        { ...config, headers }
                    );

                    const starId = starResponse.data.data[0].id;

                    for (let i = 1; i <= collectCount; i++) {
                        // 取消收藏
                        const uncollectResponse = await axios.post(
                            'https://feifan.iflytek.com/sns-service/userApi/collect/unCollect/post',
                            {
                                groupIdSet: [starId],
                                entityId: 47654
                            },
                            { ...config, headers }
                        );

                        await new Promise(resolve => setTimeout(resolve, 10000));

                        if (uncollectResponse.data.msg === 'SUCCESS') {
                            console.log(`第${i}次取消收藏成功!`);
                        } else {
                            console.log(`第${i}次取消收藏失败!`);
                        }

                        // 收藏
                        const collectResponse = await axios.post(
                            'https://feifan.iflytek.com/sns-service/userApi/collect/collect/post',
                            {
                                groupIdSet: [starId],
                                entityId: 47654
                            },
                            { ...config, headers }
                        );

                        await new Promise(resolve => setTimeout(resolve, 20000));

                        if (collectResponse.data.msg === 'SUCCESS') {
                            console.log(`第${i}次收藏成功!`);
                        } else {
                            console.log(`第${i}次收藏失败!`);
                        }
                    }
                } catch (error) {
                    console.error('收藏/取消收藏请求失败:', error);
                }
            }

            // 5. 资源下载任务
            const downloadEvent = '下载资源';
            const downloadList = await this.getObjects(headers, downloadEvent);
            const downloadCount = 1 - downloadList.length;

            if (downloadCount > 0) {
                try {
                    const downloadResponse = await axios.get(
                        'https://feifan.iflytek.com/res-service/userApi/basicRes/getResourceDownloadAddress?resourceId=2300&versionId=3527',
                        { ...config, headers }
                    );

                    if (downloadResponse.data.code === 201) {
                        console.log('下载资源成功!');
                    } else {
                        console.log('下载资源失败!');
                    }
                } catch (error) {
                    console.error('下载资源请求失败:', error);
                }
            }

            // 6. 每日阅读任务
            try {
                const postsResponse = await axios.get(
                    'https://feifan.iflytek.com/teclib-feifan-app/post/pagePostsBySubject?page=1&size=20&keyword=&orderEnum=firstPublishedTime',
                    { ...config, headers }
                );

                const posts = postsResponse.data.data.data;
                for (let i = 0; i < 10; i++) {
                    const postId = posts[i].postId;
                    await axios.get(
                        `https://feifan.iflytek.com/teclib-feifan-app/post/getPostDetail?postId=${postId}`,
                        { ...config, headers }
                    );
                }
            } catch (error) {
                console.error('阅读任务请求失败:', error);
            }

            console.log(`${feifanTokenParam.userName}执行结束！`);
        } catch (error) {
            console.error('任务执行失败:', error);
        }
    }

    /** 收藏指定的entityId */
    async collectEntity(entityId) {
        try {
            const feifanTokenParams = await this.selectAllUserToken();

            for (const feifanTokenParam of feifanTokenParams) {
                const headers = this.getBrowserHeaders(feifanTokenParam.token, entityId);
                const config = this.getRequestConfig();

                try {
                    // 获取默认收藏夹
                    const starResponse = await axios.get(
                        `https://feifan.iflytek.com/teclib-feifan-app/post/listCollectionGroup?postId=47705&username=${feifanTokenParam.userName}`,
                        { ...config, headers }
                    );

                    const starId = starResponse.data.data[0].id;

                    // 取消收藏
                    const uncollectResponse = await axios.post(
                        'https://feifan.iflytek.com/sns-service/userApi/collect/unCollect/post',
                        {
                            groupIdSet: [starId],
                            entityId: entityId
                        },
                        { ...config, headers }
                    );

                    await new Promise(resolve => setTimeout(resolve, 10000));

                    if (uncollectResponse.data.msg === 'SUCCESS') {
                        console.log(`${feifanTokenParam.userName} 取消收藏成功! entityId: ${entityId}`);
                    } else {
                        console.log(`${feifanTokenParam.userName} 取消收藏失败! entityId: ${entityId}`);
                    }

                    // 收藏
                    const collectResponse = await axios.post(
                        'https://feifan.iflytek.com/sns-service/userApi/collect/collect/post',
                        {
                            groupIdSet: [starId],
                            entityId: entityId
                        },
                        { ...config, headers }
                    );

                    await new Promise(resolve => setTimeout(resolve, 20000));

                    if (collectResponse.data.msg === 'SUCCESS') {
                        console.log(`${feifanTokenParam.userName} 收藏成功! entityId: ${entityId}`);
                    } else {
                        console.log(`${feifanTokenParam.userName} 收藏失败! entityId: ${entityId}`);
                    }
                } catch (error) {
                    console.error(`${feifanTokenParam.userName} 收藏操作失败:`, error);
                }
            }
        } catch (error) {
            console.error('收藏请求失败:', error);
        }
    }

    /** 点赞指定的entityId */
    async likeEntity(entityId) {
        try {
            const feifanTokenParams = await this.selectAllUserToken();

            for (const feifanTokenParam of feifanTokenParams) {
                const headers = this.getBrowserHeaders(feifanTokenParam.token, entityId);
                const config = this.getRequestConfig();

                const response = await axios.post(
                    'https://feifan.iflytek.com/sns-service/userApi/like/like/post',
                    {
                        entityId: entityId,
                        username: feifanTokenParam.userName
                    },
                    { ...config, headers }
                );

                await new Promise(resolve => setTimeout(resolve, 10000));

                if (response.data.msg === 'SUCCESS') {
                    console.log(`${feifanTokenParam.userName} 点赞成功! entityId: ${entityId}`);
                } else {
                    console.log(`${feifanTokenParam.userName} 点赞失败! entityId: ${entityId}`);
                }
            }
        } catch (error) {
            console.error('点赞请求失败:', error);
        }
    }

    /** 阅读指定文章 */
    async readArticle(postId) {
        try {
            const feifanTokenParams = await this.selectAllUserToken();

            for (const feifanTokenParam of feifanTokenParams) {
                const headers = this.getBrowserHeaders(feifanTokenParam.token, postId);
                const config = this.getRequestConfig();

                try {
                    await axios.get(
                        `https://feifan.iflytek.com/teclib-feifan-app/post/getPostDetail?postId=${postId}`,
                        { ...config, headers }
                    );
                    console.log(`${feifanTokenParam.userName} 阅读文章成功! postId: ${postId}`);
                } catch (error) {
                    console.error(`${feifanTokenParam.userName} 阅读文章失败:`, error);
                }
            }
        } catch (error) {
            console.error('阅读文章失败:', error);
        }
    }

    /** 获取任务记录 */
    async getObjects(headers, event) {
        const beginOfDay = dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss');
        const endOfDay = dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss');

        try {
            const response = await axios.get(
                `https://feifan.iflytek.com/teclib-score-service/userApi/score/pageScoreRecord?module=日常任务&event=${event}&startDate=${beginOfDay}&endDate=${endOfDay}`,
                { ...config, headers }
            );
            console.log('response.data.data.data', response.data.data.data);

            return response.data.data.data;
        } catch (error) {
            console.error('获取任务记录失败:', error);
            return [];
        }
    }

    /** 获取某个用户的今日任务 */
    async getObjectsByToken(token) {
        // 公共请求头
        const headers = {
            'Content-Type': 'application/json;charset=UTF-8',
            'token': token
        };

        const beginOfDay = dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss');
        const endOfDay = dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss');

        try {
            const response = await axios.get(
                `https://feifan.iflytek.com/teclib-score-service/userApi/score/pageScoreRecord?startDate=${beginOfDay}&endDate=${endOfDay}`,
                { ...config, headers }
            );
            console.log('response.data.data.data', response.data.data.data);

            return response.data.data.data;
        } catch (error) {
            console.error('获取任务记录失败:', error);
            return [];
        }
    }

    /** 某个用户阅读指定文章 */
    async readArticleByUserName(userName, postId) {
        try {
            const feifanTokenParam = await this.selectUserTokenByUsername(userName);
            const headers = this.getBrowserHeaders(feifanTokenParam.token, postId);
            const config = this.getRequestConfig();

            const response = await axios.get(
                `https://feifan.iflytek.com/teclib-feifan-app/post/getPostDetail?postId=${postId}`,
                { ...config, headers }
            );

            console.log(`${userName} 阅读文章成功! postId: ${postId}`);
            return { success: true, message: '阅读成功' };
        } catch (error) {
            console.error('阅读文章失败:', error);
            return { success: false, message: '阅读失败', error: error.message };
        }
    }

    /** 某个用户点赞指定文章 */
    async likeArticleByUserName(userName, postId) {
        try {
            const feifanTokenParam = await this.selectUserTokenByUsername(userName);
            const headers = this.getBrowserHeaders(feifanTokenParam.token, postId);
            const config = this.getRequestConfig();
            
            const response = await axios.post(
                'https://feifan.iflytek.com/sns-service/userApi/like/like/post',
                { entityId: postId, username: feifanTokenParam.userName },
                { ...config, headers }
            );
            
            if (response.data.msg === 'SUCCESS') {
                console.log(`${userName} 点赞成功! entityId: ${postId}`);
                return { success: true, message: '点赞成功' };
            } else {
                console.log(`${userName} 点赞失败! entityId: ${postId}`);
                return { success: false, message: '点赞失败' };
            }
        } catch (error) {
            console.error('点赞文章失败:', error);
            return { success: false, message: '点赞请求失败', error: error.message };
        }
    }

    /** 某个用户收藏指定文章 */
    async collectArticleByUserName(userName, postId) {
        try {
            const feifanTokenParam = await this.selectUserTokenByUsername(userName);
            const headers = this.getBrowserHeaders(feifanTokenParam.token, postId);
            const config = this.getRequestConfig();

            // 获取默认收藏夹
            const starResponse = await axios.get(
                `https://feifan.iflytek.com/teclib-feifan-app/post/listCollectionGroup?postId=47705&username=${feifanTokenParam.userName}`,
                { ...config, headers }
            );

            const starId = starResponse.data.data[0].id;

            // 先取消收藏
            await axios.post(
                'https://feifan.iflytek.com/sns-service/userApi/collect/unCollect/post',
                { groupIdSet: [starId], entityId: postId },
                { ...config, headers }
            );

            await new Promise(resolve => setTimeout(resolve, 10000));

            // 再收藏
            const collectResponse = await axios.post(
                'https://feifan.iflytek.com/sns-service/userApi/collect/collect/post',
                { groupIdSet: [starId], entityId: postId },
                { ...config, headers }
            );

            if (collectResponse.data.msg === 'SUCCESS') {
                console.log(`${userName} 收藏成功! entityId: ${postId}`);
                return { success: true, message: '收藏成功' };
            } else {
                console.log(`${userName} 收藏失败! entityId: ${postId}`);
                return { success: false, message: '收藏失败' };
            }
        } catch (error) {
            console.error('收藏文章失败:', error);
            return { success: false, message: '收藏请求失败', error: error.message };
        }
    }
}

module.exports = FeiFanService;